<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>青云教育系统 - 教师端</title>
    <link rel="stylesheet" href="../../teacher.css">
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>
</head>
<body>
    <div class="layout">
        <aside class="sidebar">
            <div class="brand">青云教育 · 教师端</div>
            <nav class="menu" id="menu">
                <button class="menu-item" data-view="profile" data-url="/index">教员信息及考勤</button>
                <button class="menu-item" data-view="schedule" data-url="/schedule">教师课表</button>
                <button class="menu-item" data-view="password" data-url="/password">修改密码</button>
                <button class="menu-item" data-view="students" data-url="/students">学生信息</button>
                <button class="menu-item" data-view="upload" data-url="/postmaterial">上传资料</button>
                <button class="menu-item" data-view="download" data-url="/downloadmaterial">下载资料</button>
                <button class="menu-item" data-view="mymaterials" data-url="/mymaterials">我的资料</button>
                <button class="menu-item" data-view="feedback" data-url="/feedback">课堂反馈</button>
                <button class="menu-item active" data-view="myfeedback" data-url="/myfeedback">我的反馈</button>
            </nav>
        </aside>
        <main class="content">
            <header class="topbar">
                <div class="left">
                    <h1 id="view-title">我的反馈</h1>
                </div>
                <div class="right">
                    <div class="user-info">
                        <img id="user-avatar" class="user-avatar" src="" alt="用户头像">
                        <span id="teacher-name" class="user-name"></span>
                    </div>
                    <button id="logoutBtn" class="btn btn-secondary">退出登录</button>
                </div>
            </header>

            <section id="view-myfeedback" class="view" style="display:block;">
                <div class="card">
                    <div class="card-header">
                        <div class="filters">
                            <div class="filter-group">
                                <label>开始日期：</label>
                                <input type="date" id="startDate">
                            </div>
                            <div class="filter-group">
                                <label>结束日期：</label>
                                <input type="date" id="endDate">
                            </div>
                            <div class="filter-group">
                                <label>关键词：</label>
                                <input type="text" id="keyword" placeholder="按课程/内容搜索">
                            </div>
                            <button id="searchFeedbackBtn" class="btn btn-primary">搜索</button>
                            <button id="resetFeedbackBtn" class="btn btn-secondary">重置</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="feedback-table-wrapper">
                            <table class="feedback-table" id="feedbackTable">
                                <thead>
                                    <tr>
                                        <th>课程名称</th>
                                        <th>上课时间</th>
                                        <th>反馈内容</th>
                                        <th>提交时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="feedbackList">
                                </tbody>
                            </table>
                        </div>
                        <div id="feedbackEmpty" class="empty" style="display:none;">暂无反馈记录</div>
                        <div id="feedbackLoading" class="loading" style="display:none;">加载中...</div>
                        <div id="pager" class="pager" style="display:flex; gap:8px; margin-top:12px; align-items:center;">
                            <button class="btn btn-secondary" id="prevPageBtn">上一页</button>
                            <span id="pageInfo">第 1 / 1 页</span>
                            <button class="btn btn-secondary" id="nextPageBtn">下一页</button>
                        </div>
                    </div>
                </div>
            </section>
        </main>
    </div>

    <script src="../../teacher.js"></script>
    <script>
        const API_BASE = 'http://localhost:8081';
        let currentPage = 1;
        let totalPages = 1;

        document.addEventListener('DOMContentLoaded', function(){
            const logoutBtn = document.getElementById('logoutBtn');
            if (logoutBtn && !logoutBtn.hasAttribute('data-bound')) {
                logoutBtn.setAttribute('data-bound', 'true');
                logoutBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (typeof logout === 'function') logout();
                });
            }

            const menu = document.getElementById('menu');
            menu.addEventListener('click', function(e){
                const btn = e.target.closest('.menu-item');
                if(!btn) return;
                const view = btn.getAttribute('data-view');
                if(view === 'schedule') window.location.href = '/teacher/schedule';
                else if(view === 'password') window.location.href = '/teacher/password';
                else if(view === 'profile') window.location.href = '/index.html';
                else if(view === 'students') window.location.href = '/teacher/students';
                else if(view === 'upload') window.location.href = '/teacher/postmaterial';
                else if(view === 'download') window.location.href = '/teacher/downloadmaterial';
                else if(view === 'mymaterials') window.location.href = '/teacher/mymaterials/';
                else if(view === 'feedback') window.location.href = '/teacher/feedback';
                else if(view === 'myfeedback') {/* 当前页 */}
            });

            document.getElementById('searchFeedbackBtn').addEventListener('click', function(){ currentPage = 1; loadFeedbackList(); });
            document.getElementById('resetFeedbackBtn').addEventListener('click', function(){
                document.getElementById('startDate').value = '';
                document.getElementById('endDate').value = '';
                document.getElementById('keyword').value = '';
                currentPage = 1; loadFeedbackList();
            });
            document.getElementById('prevPageBtn').addEventListener('click', function(){ if(currentPage>1){ currentPage--; loadFeedbackList(); }});
            document.getElementById('nextPageBtn').addEventListener('click', function(){ if(currentPage<totalPages){ currentPage++; loadFeedbackList(); }});

            loadFeedbackList();
        });

        async function loadFeedbackList(){
            try{
                toggleFeedbackLoading(true);
                
                // 模拟数据，用于测试界面
                const mockData = {
                    success: true,
                    data: [
                        {
                            endTime: "1970-01-01T17:35:00",
                            startTime: "1970-01-01T16:00:00",
                            teachDate: "2025-08-29",
                            courseName: "高一英语",
                            content: "今天英语课上学生表现很好，大部分同学都能跟上进度。张三同学在语法理解上还有困难，需要课后加强练习。",
                            createTime: "2025-08-29 18:00:00"
                        },
                        {
                            endTime: "1970-01-01T11:35:00",
                            startTime: "1970-01-01T10:00:00",
                            teachDate: "2025-08-29",
                            courseName: "高一数学",
                            content: "数学课上学生积极参与讨论，李四同学在函数概念理解上表现突出，能够举一反三。",
                            createTime: "2025-08-29 12:00:00"
                        },
                        {
                            endTime: "1970-01-01T15:35:00",
                            startTime: "1970-01-01T14:00:00",
                            teachDate: "2025-08-28",
                            courseName: "高一物理",
                            content: "物理实验课进行顺利，王五同学对实验现象观察很仔细，能够提出有深度的问题。建议增加更多实验环节。",
                            createTime: "2025-08-28 16:00:00"
                        }
                    ]
                };
                
                // 使用模拟数据
                const payload = { records: mockData.data, page: 1, totalPages: 1 };
                currentPage = payload.page || currentPage;
                totalPages = payload.totalPages || 1;
                renderFeedbackList(payload.records || []);
                updatePager();
                
                /* 原始API调用代码（注释掉用于测试）
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const token = userInfo.token || '';
                const startDate = document.getElementById('startDate').value || '';
                const endDate = document.getElementById('endDate').value || '';
                const keyword = document.getElementById('keyword').value.trim();
                const params = new URLSearchParams();
                params.append('page', String(currentPage));
                params.append('pageSize', '10');
                if(startDate) params.append('startDate', startDate);
                if(endDate) params.append('endDate', endDate);
                if(keyword) params.append('keyword', keyword);

                const res = await fetch(`${API_BASE}/feedback/list?${params.toString()}`, {
                    headers: { 'Authorization': token }
                });
                if(!res.ok){ throw new Error('加载失败'); }
                const data = await res.json();
                const payload = data && data.data ? data.data : { records: [], page: 1, totalPages: 1 };
                currentPage = payload.page || currentPage;
                totalPages = payload.totalPages || 1;
                renderFeedbackList(payload.records || []);
                updatePager();
                */
            }catch(err){
                renderFeedbackList([]);
            }finally{
                toggleFeedbackLoading(false);
            }
        }

        function renderFeedbackList(list){
            const container = document.getElementById('feedbackList');
            const empty = document.getElementById('feedbackEmpty');
            const table = document.getElementById('feedbackTable');
            
            container.innerHTML = '';
            empty.style.display = 'none';
            table.style.display = 'table';
            
            if(!list || !list.length){ 
                empty.style.display = 'block'; 
                table.style.display = 'none';
                return; 
            }
            
            list.forEach((item, index) => {
                const row = document.createElement('tr');
                const time = formatDateTime(item.createTime || item.time);
                const title = item.courseText || (item.scheduleText || '未绑定课程');
                const content = escapeHTML(item.content || '');
                const teachDate = item.teachDate || '';
                const startTime = item.startTime || '';
                const endTime = item.endTime || '';
                const courseName = item.courseName || title;
                
                // 格式化上课时间
                const classTime = teachDate ? 
                    `${teachDate} ${startTime ? startTime.substring(11, 16) : ''} - ${endTime ? endTime.substring(11, 16) : ''}` : 
                    '未设置';
                
                // 截取反馈内容，超过50字符显示省略号
                const shortContent = content.length > 50 ? content.substring(0, 50) + '...' : content;
                
                row.innerHTML = `
                    <td>
                        <div class="course-name">${courseName}</div>
                    </td>
                    <td>
                        <div class="class-time">${classTime}</div>
                    </td>
                    <td>
                        <div class="feedback-content" title="${content}">${shortContent}</div>
                    </td>
                    <td>
                        <div class="submit-time">${time}</div>
                    </td>
                    <td>
                        <button class="btn btn-pdf" onclick="generateFeedbackPdf(${item.id || index})">
                            <i class="pdf-icon">📄</i> 生成PDF
                        </button>
                    </td>
                `;
                container.appendChild(row);
            });
        }

        function updatePager(){
            document.getElementById('pageInfo').textContent = `第 ${currentPage} / ${totalPages} 页`;
        }

        function toggleFeedbackLoading(show){
            const loading = document.getElementById('feedbackLoading');
            if(loading) loading.style.display = show ? 'block' : 'none';
        }

        function formatDateTime(s){
            if(!s) return '未知时间';
            try{
                const d = new Date(s);
                return d.toLocaleDateString('zh-CN') + ' ' + d.toLocaleTimeString('zh-CN', {hour:'2-digit', minute:'2-digit'});
            }catch(e){ return s; }
        }

        function showMsg(el, msg, type='info'){
            if(!el) return;
            el.textContent = msg;
            el.className = `message ${type}`;
            el.style.display = 'block';
            setTimeout(()=>{ el.style.display='none'; }, 3000);
        }

        function escapeHTML(str){
            return (str || '').replace(/[&<>"']/g, function(m){
                return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'})[m];
            });
        }

        // PDF生成功能
        async function generateFeedbackPdf(feedbackId) {
            try {
                // 显示加载状态
                const button = event.target.closest('button');
                const originalText = button.innerHTML;
                button.disabled = true;
                button.innerHTML = '<i class="pdf-icon">⏳</i> 生成中...';
                
                // 获取用户token
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const token = userInfo.token;
                
                if (!token) {
                    alert('请先登录');
                    return;
                }
                
                // 1) 提交生成任务
                const genRes = await fetch(`${API_BASE}/pdf/feedback/${feedbackId}/generate`, {
                    method: 'POST',
                    headers: { 'Authorization': token }
                });
                const genJson = await genRes.json();
                if (!genJson || genJson.success !== true) {
                    throw new Error(genJson?.errorMsg || '提交生成任务失败');
                }

                // 2) 只轮询下载接口（202表示未就绪）
                const maxAttempts = 60;
                const intervalMs = 1500;
                for (let i = 0; i < maxAttempts; i++) {
                    const res = await fetch(`${API_BASE}/pdf/feedback/${feedbackId}/download`, {
                        method: 'GET',
                        headers: { 'Authorization': token }
                    });
                    if (res.ok) {
                        const blob = await res.blob();
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `课后反馈_${feedbackId}.pdf`;
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);
                        console.log('PDF生成成功');
                        break;
                    }
                    if (res.status !== 202) {
                        throw new Error('下载失败: ' + res.status);
                    }
                    await new Promise(r => setTimeout(r, intervalMs));
                }
            } catch (error) {
                console.error('PDF生成异常:', error);
                alert('PDF生成时发生错误');
            } finally {
                // 恢复按钮状态
                const button = event.target.closest('button');
                button.disabled = false;
                button.innerHTML = '<i class="pdf-icon">📄</i> 生成PDF';
            }
        }
    </script>
</body>
</html>


